package aom.example.security.controller;

import aom.example.security.domain.SysMenuEntity;
import aom.example.security.domain.SysRoleEntity;
import aom.example.security.domain.vo.RoleVo;
import aom.example.security.service.SysMenuService;
import aom.example.security.service.SysRoleService;
import bom.example.common.common.Results;
import bom.example.common.excetion.ResultExcetion;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiModelProperty;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.parameters.P;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author X.I.O
 * @title: RoleController
 * @projectName springboot
 * @description: TODO
 * @date 2021/10/27 19:45
 */
@Api(tags = {"角色菜单"})
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysMenuService sysMenuService;

    @Transactional
    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("角色删除")
    @PostMapping("deleterole/{id}")
    public JSONObject deleteRoleController(@PathVariable("id")String id) throws ResultExcetion{
        SysRoleEntity sysRoleEntity=sysRoleService.getById(id);
        if(sysRoleEntity==null){
            throw new ResultExcetion(1,"角色不存在");
        }
        if("ADMIN".equals(sysRoleEntity.getRoleName())){
            throw new ResultExcetion(1,"管理员角色不得修改");
        }
        sysRoleService.deleteSysRoleMenuByRoleId(id);
        sysRoleService.removeById(id);
        return Results.success("删除成功");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("角色修改")
    @PostMapping("updaterole")
    public JSONObject updateRoleController(@RequestBody SysRoleEntity sysRoleEntity) throws ResultExcetion{
        SysRoleEntity sysRoleEntity1=sysRoleService.getById(sysRoleEntity.getRoleId());
        if(sysRoleEntity1==null){
            throw new ResultExcetion(1,"请刷新系统后重试");
        }
        if("ADMIN".equals(sysRoleEntity1.getRoleName())){
            throw new ResultExcetion(1,"管理员角色不能修改");
        }
        sysRoleService.updateById(sysRoleEntity);
        return Results.success("修改成功");
    }


    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("获取单个角色")
    @PostMapping("getroleone/{id}")
    public JSONObject getRoleOneController(@PathVariable("id")String id){
        SysRoleEntity sysRoleEntity=sysRoleService.getById(id);
        return Results.success(sysRoleEntity);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @PostMapping("/roleList")
    @ApiOperation("角色分页列表")
    public JSONObject rolePageListController(@ApiParam("页码") @RequestParam("pageNum")Integer pageNum,
                                             @ApiParam("条数")@RequestParam("pageSize")Integer pageSize,
                                             @ApiParam("关键字")@RequestParam("keyword")String keyword){
        LambdaQueryWrapper<SysRoleEntity> lambdaQueryWrapper=new LambdaQueryWrapper();
        if(StringUtils.isNotBlank(keyword)){
            lambdaQueryWrapper.or().like(SysRoleEntity::getRoleName,keyword);
        }
        lambdaQueryWrapper.orderByDesc(SysRoleEntity::getCreateDate);
        Page page=new Page(pageNum,pageSize);
        IPage<SysRoleEntity> sysRoleEntityIPage=sysRoleService.page(page,lambdaQueryWrapper);
        return Results.success(sysRoleEntityIPage.getRecords(),sysRoleEntityIPage.getTotal());
    }

    @ApiOperation("角色添加")
    @PostMapping("/addRole")
    public JSONObject roleAddController(@RequestBody RoleVo roleVo){
        SysRoleEntity sysRoleEntity=new SysRoleEntity();
        BeanUtils.copyProperties(roleVo,sysRoleEntity);
        sysRoleService.save(sysRoleEntity);
        return Results.success();
    }


    /**
     * 查询用户不具有的权限
     * @param uid
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("角色下拉列表")
    @PostMapping("roleselect/{uid}")
    public JSONObject roleMapList(@ApiParam("用户id")@PathVariable("uid")String uid){
       List<Map<String, Object>> mapList=sysRoleService.selectUserNotRole(uid);
       JSONArray array=new JSONArray();
        for (int i = 0; i < mapList.size() ; i++) {
            Map<String, Object> map=mapList.get(i);
            JSONObject object=new JSONObject();
            String id=String.valueOf(map.get("role_id"));
            String roleName=String.valueOf(map.get("role_name"));
            object.put("key",id);
            object.put("value",roleName);
            array.add(object);;
        }
        return Results.success(array);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("获取当前用户角色列表")
    @PostMapping("getuserrole/{uid}")
    public JSONObject getUserRoleListController(@ApiParam("用户id")@PathVariable("uid")String uid){
        List<Map<String, Object>> maps=sysRoleService.selectRoleUserByUserId(uid);
        return Results.success(maps);
    }

    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("添加角色通过用户id")
    @PostMapping("addroleuser")
    public JSONObject addUserRoleController(@ApiParam("用户id")@RequestParam("userId") String userId,
                                            @ApiParam("角色id")@RequestParam("roieId") String roieId){
        sysRoleService.insertSysUserRole(userId,roieId);
        return Results.success();
    }

    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("删除用户角色通过id")
    @PostMapping("deleteroleuser/{id}")
    public JSONObject deleteUserRoleByIdController(@PathVariable("id")String id){
        sysRoleService.deleteSysUserRoleById(id);
        return Results.success();
    }

    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("角色关联权限")
    @PostMapping("rolemenu")
    public JSONObject addRoleMenuController(@RequestBody Map map)throws ResultExcetion{
        String menuId=String.valueOf(map.get("menuId"));
        String roleId=String.valueOf(map.get("roleId"));
        SysMenuEntity sysMenuEntity=sysMenuService.getBaseMapper()
                .selectOne(new LambdaQueryWrapper<SysMenuEntity>().eq(SysMenuEntity::getMenuId,menuId).isNotNull(SysMenuEntity::getMenu)
                .isNull(SysMenuEntity::getDictory));
        if(sysMenuEntity==null){
            throw new ResultExcetion(1,"资源不存在");
        }
        SysRoleEntity sysRoleEntity=sysRoleService.getById(roleId);
        if(sysRoleEntity==null){
            throw new ResultExcetion(1,"角色信息不存在");
        }
        sysRoleService.insertSysRoleMenu(roleId,menuId);
        return Results.success("新增成功");
    }

    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("解除角色与菜单授权")
    @PostMapping("/delete/{id}")
    public JSONObject removeRoleMenuController(@PathVariable("id")Integer id){
        sysRoleService.deleteRoleMenuById(id);
        return Results.success("解除授权成功");
    }


    @PreAuthorize("hasRole('ADMIN')")
    @ApiOperation("角色用户授权分页列表")
    @PostMapping("sysuserrolepage")
    public JSONObject sysRoleUserPageController(@RequestParam("pageNum")Integer pageNum,
                                                @RequestParam("pageSize")Integer pageSize,
                                                @RequestParam("userId")String userId,
                                                @RequestParam(value = "keyword",required = false)String keyword){
        IPage<Map<String, Object>> mapIPage=sysRoleService.pageRoleUser(userId,keyword,pageNum,pageSize);
        mapIPage.getRecords().forEach(e->{
            if(e.get("id")==null){
                e.put("code",0);
            }else {
                e.put("code",1);
            }
        });
        return Results.success(mapIPage.getRecords(),mapIPage.getTotal());
    }



}
